<!DOCTYPE html>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:set var="ok" value="%{getText(\"button.ok\")}" />
<s:set var="cancel" value="%{getText(\"button.cancel\")}" />
<s:set var="updateSuccessfulMsg"
  value="%{getText('info.update.successful', {getText('title.product')})}" />
<s:set var="requiredMsg" value="%{getText('error.required')}" />
<link href="${pageContext.request.contextPath}/css/ui.multiselect.ext.css" rel="stylesheet"
  type="text/css" />
<script type="text/javascript">
  function loadProductCategories() {
    jQuery
        .ajax({
          url : '${pageContext.request.contextPath}/inventory/productCategory/getProductCategories.action',
          dataType : 'json',
          async : false,
          cache : true,
          data : {
            rows : -1,
            page : 1,
          },
          success : function(data) {
            var categories = $('#categories');
            categories.empty();
            $.each(data.rows,function(idx,record) {
              categories.append($('<option />').val(record.id).text(record.name));
            });
            categories.multiselect('refresh');
          }
        });
  }

  function focusOnFirstElement() {
    setTimeout(function() {
      $('#product-dialog-form :input:visible:enabled:first').focus();
    },10);
  }

  function refreshProduct() {
    var id = $('#id').val();
    jQuery.ajax({
      url : '${pageContext.request.contextPath}/inventory/product/loadProduct.action',
      dataType : 'json',
      async : false,
      cache : true,
      data : {
        'product.id' : $('#id').val()
      },
      success : function(data) {
        var version = data.version;
        var name = data.name;
        var selected = data.categories;
        $('#name').val(name);
        $('#version').val(version);
        var categories = $('#categories');
        categories.find('option:selected').removeProp('selected');
        if (selected) {
          $.each(selected,function(idx,val) {
            categories.find('option').filter(function() {
              return val.id == $(this).val();
            }).prop('selected','selected');
          });
          categories.multiselect('refresh');
        }
      }
    });
  }

  $(function() {
    $(':input:not(:hidden)').prop('autocomplete','off');
    $('#productMsg').tooltip({
      tooltipClass : "ui-state-highlight"
    });
    $('#addProductButtonDiv').addClass('ui-dialog-buttonset');
    $('.submit-button').button();
    $('#productOkBtn').click(function(e) {
      e.preventDefault();
      var bValid = $('#product-form').valid();
      if (bValid) {
        var params = {};
        params['product.id'] = $('#id').val();
        params['product.version'] = $('#version').val();
        params['product.name'] = $('#name').val();
        $('#categories option:selected').each(function(idx) {
          params['product.categories[' + idx + '].id'] = $(this).val();
        });
        jQuery.ajax({
          url : '${pageContext.request.contextPath}/inventory/product/updateProduct.action',
          type : 'POST',
          dataType : 'json',
          cache : false,
          data : params,
          success : function(data) {
            var msg = '';
            var status = data.status;
            if (status == 'SUCCESS') {
              if (data.attrs.version) {
                var version = data.attrs.version;
                $('#version').val(version);
              }
              $('#listProduct').trigger('reloadGrid');
              $('#productCancelBtn').trigger('click');
            } else if (status == 'ERROR') {
              if (data.errors) {
                var errors = data.errors;
                for ( var i = 0; i < errors.length; i++) {
                  msg += errors[i];
                  if (i < errors.length - 1) {
                    msg += ', ';
                  }
                }
              }
              $('#productMsg').attr('title',msg).tooltip('open');
              setTimeout(function() {
                $('#productMsg').tooltip("close").attr("title","");
              },1500);
            }

          }
        });
      }
    });
    $('#productCancelBtn').click(function(e) {
      e.preventDefault();
      $('#editProduct').empty();
      $('#mainListProduct').show();
    });
    $("#productAccordion").multipleaccordion();
    $('#productAccordion > div > table td.LABEL').css({
      'width' : '130px'
    });
    $('input, select, textarea, button').not(':hidden').each(function(idx) {
      $(this).prop('tabindex',idx + 1);
    });
    $('#product-dialog-form').wrap('<form id="product-form">');
    $.validator.setDefaults({
      errorClass : 'ui-state-error',
      errorPlacement : function(error,element) {
        if (element.context.id.indexOf('_combobox') == -1) {
          error.insertAfter(element.parent().children(':last'));
        } else {
          error.appendTo(element.parent());
        }
      }
    });
    $('#product-form').validate(
        {
          ignore : '',
          rules : {
            'product.name' : {
              required : true
            },
            'product.categories' : {
              required : true
            }
          },
          messages : {
            'product.name' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.product.name\")}" />')
            },
            'product.categories' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.product.category.name\")}" />')
            }
          }
        });
    $('#categories').addClass('multiselect');
    $('#categories').multiselect();
    loadProductCategories();
    refreshProduct();
    focusOnFirstElement();
  });
</script>
<div id="product-dialog-form" title='<s:property value="getText('title.edit.product')"/>'>
  <div id="productMsg"></div>
  <div id="productAccordion">
    <h3>
      <s:property value="getText('title.product.item')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="product.name" class="mandatory"><input
              type="hidden" id="version" name="product.version" /> <input type="hidden" id="id"
              name="product.id" value='<s:property value="%{#parameters[\"product.id\"]}" />' /> <s:property
                value="getText('field.product.name')" /></label></td>
          <td><input type="text" id="name" name="product.name" maxlength="100"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="product.category" class="mandatory"><s:property
                value="getText('field.product.category.name')" /></label></td>
          <td><select id="categories" name="product.categories" multiple="multiple"></select></td>
        </tr>
      </table>
    </div>
  </div>
  <div id="addProductButtonDiv">
    <button id="productOkBtn" class="submit-button">
      <s:property value="getText('button.ok')" />
    </button>
    <button id="productCancelBtn" class="submit-button">
      <s:property value="getText('button.cancel')" />
    </button>
  </div>
</div>
